package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import com.hmdp.service.ILock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * 自定义分布式锁
 * @Author LiJunXi
 * @Date 2024-03-10 16:55
 */
public class SimpleRedisLock implements ILock {

    private static final String kEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> defaultRedisScript;
    static {
        defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setLocation(new ClassPathResource("unlock.lua"));
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public Boolean tryLock(Long time) {
        // 获取锁
        // 获取线程ID
        String id = ID_PREFIX + Thread.currentThread().getId();
        // value值不能只用线程ID，因为集群模式下不同的JVM的的锁是不同的，ID都是自增的，会出现重复的ID，需要加个随机数前缀，防止误删
        return stringRedisTemplate.opsForValue().setIfAbsent(kEY_PREFIX + name, id, time, TimeUnit.SECONDS);
    }

//    @Override
//    public void unLock() {
//        // 防止分布式锁误删
//        String s = stringRedisTemplate.opsForValue().get(kEY_PREFIX + name);
//        if (s.equals(ID_PREFIX + Thread.currentThread().getId())){
//            stringRedisTemplate.delete(kEY_PREFIX + name);
//        }
//    }

    @Override
    public void unLock() {
        // 采用lua脚本解决原子性问题
        stringRedisTemplate.execute(defaultRedisScript, Collections.singletonList(kEY_PREFIX + name), ID_PREFIX + Thread.currentThread().getId());
    }
}
